package com.lb.jwitter.service;

import java.io.Serializable;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import javax.jws.WebService;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.lb.jwitter.*;
import com.lb.jwitter.hibernate.*;
import com.lb.jwitter.util.ChumanoLogger;
import com.lb.jwitter.util.ConditionReport;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import net.sf.json.JSONSerializer;

@Service("tbl_ThongTin_MonHocService")
@Transactional
@WebService(endpointInterface = "com.lb.jwitter.service.Tbl_ThongTin_MonHocService")
public class Tbl_ThongTin_MonHocServiceImpl implements
		Tbl_ThongTin_MonHocService, Serializable {

	private Log log = LogFactory.getLog(Tbl_ThongTin_MonHocServiceImpl.class);
	private static final long serialVersionUID = -8740095022264495229L;

	@Autowired
	@Qualifier("tbl_ThongTin_MonHocDAO")
	private Tbl_ThongTin_MonHocDAO _tbl_ThongTin_MonHocDao;
	
	@Autowired
	@Qualifier("tbl_ThongTin_TKBDAO")
	private Tbl_ThongTin_TKBDAO _tbl_ThongTin_TKBDao;
	
	@Autowired
	@Qualifier("tbl_ThongTin_NhomLop_MonHocDAO")
	private Tbl_ThongTin_NhomLop_MonHocDAO _tbl_ThongTin_NhomLop_MonHocDao;

	@Autowired
	@Qualifier("tbl_CTDT_MonHocDAO")
	private Tbl_CTDT_MonHocDAO _tbl_CTDT_MonHocDao;

	@Autowired
	@Qualifier("tbl_CanBoDAO")
	private Tbl_CanBoDAO _tbl_CanBoDao;

	public final List<Tbl_ThongTin_MonHoc> findAlltbl_ThongTin_MonHoc(
			int pageSize, int page) {
		List<Tbl_ThongTin_MonHoc> result = get_tbl_ThongTin_MonHocDao()
				.findAll(pageSize, page);
		log.info("Number of user in DB:: " + result.size());
		return result;
	}

	@Transactional(noRollbackFor = IllegalArgumentException.class)
	public final Long createtbl_ThongTin_MonHoc(Tbl_ThongTin_MonHoc obj) {
		return _tbl_ThongTin_MonHocDao.save(obj);
	}

	public final void updatetbl_ThongTin_MonHoc(Tbl_ThongTin_MonHoc obj) {
		_tbl_ThongTin_MonHocDao.update(obj);
	}// end update methode

	public final Tbl_ThongTin_MonHoc gettbl_ThongTin_MonHoc(Long id) {
		log.info("Try to retrieve the tbl_ThongTin_MonHoc: " + id);
		return get_tbl_ThongTin_MonHocDao().get(id);
	}

	public void deletetbl_ThongTin_MonHoc(Long id) {
		log.info("Try to delete the tbl_ThongTin_MonHoc by Id : " + id);
		if (_tbl_ThongTin_MonHocDao.exists(id)) {
			_tbl_ThongTin_MonHocDao.delete(id);
		} else {
			throw new IllegalArgumentException("EmployeeId '" + id
					+ "' does not exists");
		}
	}

	public void createListtbl_ThongTin_MonHocByJSON(int dotDKId, String data,
			Tbl_TaiKhoan taiKhoan) {
		try{
		ChumanoLogger.init(Tbl_ThongTin_MonHocServiceImpl.class.getName());
		ChumanoLogger.log("0BAT DAU INSERT DU LIEU");
		List<Tbl_ThongTin_MonHoc> tbl_ThongTin_MonHocs = new ArrayList<Tbl_ThongTin_MonHoc>();
		List<Tbl_ThongTin_NhomLop_MonHoc> tbl_ThongTin_NhomLop_MonHocs = new ArrayList<Tbl_ThongTin_NhomLop_MonHoc>();
		
		JSONArray jsons = (JSONArray) JSONSerializer.toJSON(data);

		Tbl_DKMH_DotDK tblDKMHDotDK = new Tbl_DKMH_DotDK();
		tblDKMHDotDK.setId(new Long(dotDKId));
		ArrayList<String> monhocmos = new ArrayList<String>();
		for (int i = 0; i < jsons.size(); i++) {
			JSONObject obj = jsons.getJSONObject(i);
			// F_MAMH F_MANH F_SISO F_TUANDAU F_TUANCUOI
			// T1 T2 .......... T26
			// F_MANHKEM F_TO
			//PTMoRong	PTTachLop
			// -----------------Lay du lieu--------------------------
			String maMH = obj.getString("F_MAMH");maMH=maMH.trim();
			String maNhom = obj.getString("F_MANH");
			int siso = Integer.parseInt(obj.getString("F_SISO"));
			int tuandau = Integer.parseInt(obj.getString("F_TUANDAU"));
			int tuancuoi = Integer.parseInt(obj.getString("F_TUANCUOI"));
			String maNhomKem = obj.getString("F_MANHKEM");
			String maTo = obj.getString("F_TO");
			
			String s1 = obj.getString("PTMORONG");
			String s2 = obj.getString("PTTACHLOP");
			double ptMoRong = Double.parseDouble(s1.isEmpty()?"0": obj.getString("PTMORONG"));
			double ptTachLop = Double.parseDouble(s2.isEmpty()?"0": obj.getString("PTTACHLOP"));
			
			String maCoSo = obj.getString("DIADIEM");

			int sotuanhoc = 26;
			int tuanhoc = 0;
			for (int j = 1; j <= sotuanhoc; j++) {
				String hoc = obj.getString("T" + j);
				if (hoc.equals("x")) {
					tuanhoc += (int) Math.pow(2, sotuanhoc - j);
				}
			}
			
			String logStr ="[ " + (i+1)+ " - " 
			+ "MONHOC: " + maMH + " - " 
			+ "NHOM: " + maNhom + " - " 
			+ "SISO: " + siso + " - " 
			+ "TUANBAU: " + tuandau + " - " 
			+ "TUANCUOI: " + tuancuoi + " - " 
			+ "NHOMKEM: " + maNhomKem + " - " 
			+ "TONHOM: " + maTo + " - " 
			+ "TUANHOC: " + Integer.toBinaryString(tuanhoc)
			+ "]";
			// get mon hoc theo ma mon hoc
			

			Tbl_CTDT_MonHoc monhoc = findMonHoc(maMH);

			if(monhoc==null){
				ChumanoLogger.log(logStr+ " <NOT MONHOC>");
				continue;
			}			

			//===============================================
			//tim de update
			Tbl_ThongTin_NhomLop_MonHoc tbl_ThongTin_NhomLop_MonHoc = findNhomLopMonHoc(new Long(dotDKId), maMH, maNhom);
			
			if(!monhocmos.contains(maMH)){
				Tbl_ThongTin_MonHoc tblThongTinMonHoc = findThongTinMonHoc(new Long(dotDKId),maMH);
				//===============================================
				//--------------TblThongTinMonHoc-------------------
				if(tblThongTinMonHoc==null){ 
					tblThongTinMonHoc = new Tbl_ThongTin_MonHoc();
					tblThongTinMonHoc.setMonHocId(monhoc);
					tblThongTinMonHoc.setDotDKId(tblDKMHDotDK);
					tblThongTinMonHoc.setCanBoId(taiKhoan.getCanBoId());
					tblThongTinMonHoc.setNgayCapNhat(new Date());
		
					tbl_ThongTin_MonHocs.add(tblThongTinMonHoc);
					logStr+= " [NEW MONHOC]";
					monhocmos.add(maMH);
				}
			}
			ChumanoLogger.log(logStr);
			
			//--------------TblThongTinTKB-------------
			Tbl_ThongTin_TKB tbl_ThongTin_TKB;
			if(tbl_ThongTin_NhomLop_MonHoc== null)
				tbl_ThongTin_TKB = new Tbl_ThongTin_TKB();
			else{
				tbl_ThongTin_TKB = tbl_ThongTin_NhomLop_MonHoc.getTKBId();
			}
			tbl_ThongTin_TKB.setCanBoId(taiKhoan.getCanBoId());
			tbl_ThongTin_TKB.setDotDKId(tblDKMHDotDK);
			tbl_ThongTin_TKB.setNgayCapNhat(new Date());
			
			tbl_ThongTin_TKB.setSiSoMax(siso); //siso
			tbl_ThongTin_TKB.setSiSoMin(0);
			tbl_ThongTin_TKB.setSoHVDangKy(0); //sodk
			
			tbl_ThongTin_TKB.setPhanTramXepLop(ptMoRong);
			tbl_ThongTin_TKB.setPhanTramDoi(ptTachLop);
			
			tbl_ThongTin_TKB.setTuanBatDau(tuandau);//tuanbd
			tbl_ThongTin_TKB.setTuanKetThuc(tuancuoi);//tuanketthuc
			tbl_ThongTin_TKB.setTuanHoc(tuanhoc);//tuanhoc - ko dung nua
			
			tbl_ThongTin_TKB.setMaCoSo(maCoSo); //macoso - dung qua cho chitiet

			if(tbl_ThongTin_NhomLop_MonHoc== null){
				Long tkbid = _tbl_ThongTin_TKBDao.save(tbl_ThongTin_TKB);
				tbl_ThongTin_TKB.setId(tkbid);
			}else{
				_tbl_ThongTin_TKBDao.update(tbl_ThongTin_TKB);
			}
			
			//--------------TblThongTinNhomLopMonHoc-------------
			if(tbl_ThongTin_NhomLop_MonHoc==null) tbl_ThongTin_NhomLop_MonHoc = new Tbl_ThongTin_NhomLop_MonHoc();
			tbl_ThongTin_NhomLop_MonHoc.setMonHocId(monhoc);
			tbl_ThongTin_NhomLop_MonHoc.setMa(maNhom);
			tbl_ThongTin_NhomLop_MonHoc.setToNhom(maTo);
			tbl_ThongTin_NhomLop_MonHoc.setTen(maMH+"_"+maNhom);
			
			tbl_ThongTin_NhomLop_MonHoc.setDotDKId(tblDKMHDotDK);
			tbl_ThongTin_NhomLop_MonHoc.setCanBoId(taiKhoan.getCanBoId());
	        tbl_ThongTin_NhomLop_MonHoc.setNgayCapNhat(new Date());
	        tbl_ThongTin_NhomLop_MonHoc.setTKBId(tbl_ThongTin_TKB);
	        
	        tbl_ThongTin_NhomLop_MonHocs.add(tbl_ThongTin_NhomLop_MonHoc);
			
		}// end for
		
		//----------------------------------------------------------------------
		//luu thong tin mon hoc
		_tbl_ThongTin_MonHocDao.saveOrUpdateAll(tbl_ThongTin_MonHocs);
		
		//luu thongtin_nhomlop_monhoc
		_tbl_ThongTin_NhomLop_MonHocDao.saveOrUpdateAll(tbl_ThongTin_NhomLop_MonHocs);
		}
		catch (Exception e) {
			// TODO: handle exception
			   ChumanoLogger.log("ERROR: " +e.getMessage());
			   System.out.println("------------ERROR CHUMANO-------------");
			   e.printStackTrace();
			   System.out.println("=================================");
		}
		   
		ChumanoLogger.stop();
	}

	private Tbl_CTDT_MonHoc findMonHoc(String ma){
		if(ma==null|| ma.equals("")) return null;
		
		List<ConditionReport> cons = new ArrayList<ConditionReport>();
		{
        	 ConditionReport con = new ConditionReport(); 
             con.setCol("ma");
             con.setValue1(ma);
             con.setOperator("eq");
             cons.add(con);	
        }
        List<String> columns = new ArrayList<String>();
        columns.add("id");
        
        List<Long> ids = _tbl_CTDT_MonHocDao.findColumnByCondition(Tbl_CTDT_MonHoc.class,cons,columns, 1, 1);
        
        if(ids==null||ids.size()==0) return null;
        //--------------------
        Tbl_CTDT_MonHoc obj  = new Tbl_CTDT_MonHoc();
        obj.setId(ids.get(0));
        obj.setMa(ma);
        
        return obj;
	}
	
	private Tbl_ThongTin_NhomLop_MonHoc findNhomLopMonHoc(Long dotDKid, String maMH, String maNhom){
		if(maMH==null|| maMH.equals("") || maNhom==null|| maNhom.equals("")) return null;
		
		List<ConditionReport> cons = new ArrayList<ConditionReport>();
		{
        	 ConditionReport con = new ConditionReport(); 
             con.setCol("monHocId.ma");
             con.setValue1(maMH);
             con.setOperator("eq");
             cons.add(con);	
        }
		
		{
       	 ConditionReport con = new ConditionReport(); 
            con.setCol("ma");
            con.setValue1(maNhom);
            con.setOperator("eq");
            cons.add(con);	
        }
		
		{
	       	 ConditionReport con = new ConditionReport(); 
            con.setCol("dotDKId.id");
            con.setValue1(dotDKid);
            con.setOperator("eq");
            cons.add(con);	
	    }

        
        List<Tbl_ThongTin_NhomLop_MonHoc> nlmhs =_tbl_ThongTin_NhomLop_MonHocDao.findByCondition(Tbl_ThongTin_NhomLop_MonHoc.class,cons, 1, 1);
        
        if(nlmhs==null||nlmhs.size()==0) return null;
        //--------------------
        
        return nlmhs.get(0);
	}

	private Tbl_ThongTin_MonHoc findThongTinMonHoc(Long dotDKid, String maMH){
		if(maMH==null|| maMH.isEmpty()) return null;
		
		List<ConditionReport> cons = new ArrayList<ConditionReport>();
		{
        	 ConditionReport con = new ConditionReport(); 
             con.setCol("monHocId.ma");
             con.setValue1(maMH);
             con.setOperator("eq");
             cons.add(con);	
        }
		
		{
	        ConditionReport con = new ConditionReport(); 
            con.setCol("dotDKId.id");
            con.setValue1(dotDKid);
            con.setOperator("eq");
            cons.add(con);	
	    }

        
        List<Tbl_ThongTin_MonHoc> ttmhs =_tbl_ThongTin_MonHocDao.findByCondition(Tbl_ThongTin_MonHoc.class,cons, 1, 1);
        
        
        if(ttmhs==null||ttmhs.size()==0) {
        	//ChumanoLogger.log("Tim khong thay: " + maMH);
        	return null;
        }
        //--------------------
        
        return ttmhs.get(0);
	}
	
	//=========================================================================
	public void deleteListtbl_ThongTin_MonHoc(String[] listId) {
		for (String id : listId) {
			deletetbl_ThongTin_MonHoc(Long.parseLong(id));
		}
	}

	public List<Tbl_ThongTin_MonHoc> findtbl_ThongTin_MonHocByCondition(
			List<ConditionReport> cons, int pageSize, int page) {
		return _tbl_ThongTin_MonHocDao.findByCondition(
				Tbl_ThongTin_MonHoc.class, cons, pageSize, page);
	}

	
	
	public int counttbl_ThongTin_MonHocByCondition(List<ConditionReport> cons) {
		return _tbl_ThongTin_MonHocDao.countByCondition(
				Tbl_ThongTin_MonHoc.class, cons);
	}

	public final Tbl_ThongTin_MonHocDAO get_tbl_ThongTin_MonHocDao() {
		return _tbl_ThongTin_MonHocDao;
	}

	public final void set_tbl_ThongTin_MonHocDao(Tbl_ThongTin_MonHocDAO obj) {
		this._tbl_ThongTin_MonHocDao = obj;
	}

	public Tbl_CTDT_MonHocDAO get_tbl_CTDT_MonHocDao() {
		return _tbl_CTDT_MonHocDao;
	}

	public void set_tbl_CTDT_MonHocDao(Tbl_CTDT_MonHocDAO _tbl_CTDT_MonHocDao) {
		this._tbl_CTDT_MonHocDao = _tbl_CTDT_MonHocDao;
	}

	public Tbl_CanBoDAO get_tbl_CanBoDao() {
		return _tbl_CanBoDao;
	}

	public void set_tbl_CanBoDao(Tbl_CanBoDAO _tbl_CanBoDao) {
		this._tbl_CanBoDao = _tbl_CanBoDao;
	}

}// endclass

